/*
 * @Author: xgq
 * @Date: 2020-05-12 16:41:04
 * @LastEditTime: 2020-09-06 09:49:06
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \tuyibo\servers\api\wbms\tagIcon.js
 */
var express = require('express');
var tagIcon_router = express.Router();
var db = require('../../models');
const sequelize = require('sequelize');
const Op = require('sequelize').Op;
var comm = require('../../comm')


// 单个图片添加单个标签
/**  
 * @author: xgq
 * @description: 
 * @param {type} 
 * @return: 
 */
tagIcon_router.post('/addTag', async (req, res) => {
  var [icon_id, tag_name, tag_id] = [req.body.icon_id, req.body.tag.name, req.body.tag.tag_id]
  tag_name = tag_name.trim()
  var result={code:'',data:''}
  if (tag_id == undefined) {//如果tagId为空，说明是新建的标签,需要添加事务
    result.data = await db.tag.sequelize.transaction(t => {
      return db.tag.create({ name: tag_name }, { transaction: t })
        .then(data => {
          let id = data.dataValues.id
          var tag_name = data.dataValues.name
          comm.redis.set(id, tag_name, function () { })
          return db.tagIcon.create({ icon_id, tag_id: id, tag_name }, { transaction: t }).then(() => {
            //更新图标的tagIds
            //获取图标的所有标签Id
            return db.tagIcon.findOne({
              attributes: [
                ['icon_id', 'id'],
                [sequelize.fn('group_concat', sequelize.col('tag_id')), 'tagIds']
              ],
              raw: true,
              where: {
                'icon_id': icon_id
              },
              transaction: t
            }).then(icon => {
              //更新图标的TagIds
              return db.icons.update(
                { tagIds: icon.tagIds },
                {
                  where: {
                    "id": icon_id
                  },
                  transaction: t
                }
              ).then(() => {
                return true
              }).catch(err => {
                console.log(err)
              })
            })
          })
        })
    })
  } else {// 否则只要添加到关系表即可
    result.data = await db.sequelize.transaction(t => {
      return db.tagIcon.create({ icon_id, tag_id: tag_id, tag_name }, { transaction: t }).then(() => {
        //更新图标的tagIds
        //获取图标的所有标签Id
        return db.tagIcon.findOne({
          attributes: [
            ['icon_id', 'id'],
            [sequelize.fn('group_concat', sequelize.col('tag_id')), 'tagIds']
          ],
          raw: true,
          where: {
            'icon_id': icon_id
          },
          transaction: t
        }).then(icon => {
          //更新图片的TagIds
          return db.icons.update(
            { tagIds: icon.tagIds },
            {
              where: {
                "id": icon_id
              },
              transaction: t
            }
          ).then(() => {
            return true
          }).catch(err => {
            console.log(err)
          })
        })
      })
    })
  }
  if (result.data !== undefined) result.code = 1
  res.json(result)
})


/**
 * @author: xgq
 * @description: 删除多个图片和标签的关系
 * 1. 删除图片关系表的关系
 * 2. 获取所有图片的tagIds
 * 3. 更新图片表的tagIds字段
 * @param {type} 
 * @return: 
 */
tagIcon_router.post('/deleteTags', async (req, res) => {
  let ids = req.body.ids
  let tag_id = req.body.tag_id
  let result = await db.sequelize.transaction(t => {
    return db.tagIcon.destroy({
      where: {
        "icon_id": {
          [Op.in]: ids
        },
        "tag_id": tag_id
      },
      transaction: t
    }).then(() => {
      return db.tagIcon.findAll({
        attributes: [
          ['icon_id', 'id'],
          [sequelize.fn('group_concat', sequelize.col('tag_id')), 'tagIds']
        ],
        raw: true,
        where: {
          'icon_id': {
            [Op.in]: ids
          }
        },
        group: 'icon_id',
        transaction: t
      }).then(icons => {
        return db.icons.bulkCreate(
          icons,
          {
            updateOnDuplicate: ["id", 'tagIds'],
            transaction: t
          },
        ).then(() => {
          return true
        })
      })
    })
  }).then(re => {
    return true
  }).catch(err => {
    return false
  })
  res.json(result)
})

/**
 * @author: xgq
 * @description: 增加多个图片和标签的关系
 * 1. 不能在关系表重复添加数据
 * 2. 
 * @param {type} 
 * @return: 
 */
tagIcon_router.post('/groupAddTags', async (req, res) => {
  var ids = req.body.ids
  var tags = req.body.tags
  for(let item in tags){
    if(typeof(tags[item])=='string'){
      var target=await db.tag.findCreateFind({where:{ name: tags[item] },defaults:{name:tags[item]}}).then(result=>{
        comm.redis.set(result[0].dataValues.id, result[0].dataValues.name, function () { })
        return result[0].dataValues
      })
      tags[item]=target
    }
  }
  var tagImages=structData(ids,tags)
  await db.sequelize.transaction(t => {
    var promises = []
    tagImages.forEach( item => {
      var result =  db.tagIcon.findCreateFind({
        where: { tag_id: item.tag_id, icon_id: item.icon_id },
        defaults: { tag_id: item.tag_id, icon_id: item.icon_id, tag_name: item.tag_name },
        transaction: t
      })
      promises.push(result)
    });
    return Promise.all(promises).then( () => {
      return  db.tagIcon.findAll({
        attributes: [
          ['icon_id', 'id'],
          [sequelize.fn('group_concat', sequelize.col('tag_id')), 'tagIds']
        ],
        raw: true,
        where: {
          'icon_id': {
            [Op.in]: ids
          }
        },
        group: 'icon_id',
        transaction: t
      }).then(imgs => {
        return db.icons.bulkCreate(
          imgs,
          {
            updateOnDuplicate: ["id", 'tagIds'],
            transaction: t
          },
        ).then(() => {
          return true
        })
      })
    })
  }).then(re => {
    res.json(tags)
  }).catch(err => {
    res.json('操作失败')
  })
})


let structData = (Ids, newTags)=> {
  var resultData = [];
  for (let item of Ids) {
    for (let tag of newTags) {
      resultData.push({
        icon_id: item,
        tag_id: tag.id,
        tag_name: tag.name
      });
    }
  }
  return resultData;
}



module.exports = tagIcon_router